﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace tomvangaever.CorrelationWebPart
{
    public class ULSHelper
    {

        private string[] _headers = new string[] { 
            "Timestamp",
            "Process",
            "TID",
            "Area",
            "Category",
            "EventID",
            "Level",
            "Message",
            "Correlation"
        };

        public DataTable BuildDataTable(string fileName)
        {
            try
            {
                // Generate the table columns
                DataTable entries = new DataTable("Entries");
                foreach (var header in _headers) { 
                    entries.Columns.Add(header, header.GetType());
                }
                
                //check the modified date of the log
                var file = new FileInfo(fileName);
                var lstmodifieddate = file.LastWriteTime;
                var usefile = lstmodifieddate.AddDays(5) > DateTime.Now ;

                // leave the PSCDiagnostics out of the ULS log
                if (!file.Name.StartsWith("PSCDiagnostics") && usefile)
                {
                    FileStream logFile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    using (StreamReader reader = new StreamReader(logFile))
                    {
                        var line = reader.ReadLine();
                        if (!string.IsNullOrEmpty(line))
                        {
                            while (!reader.EndOfStream)
                            {
                                string[] fields = reader.ReadLine().Split(new char[] { '\t' });
                                DataRow r = entries.Rows.Add(fields);
                                if (r["Timestamp"].ToString().EndsWith("*"))
                                {
                                    entries.Rows[entries.Rows.Count - 2]["Message"] = entries.Rows[entries.Rows.Count - 2]["Message"].ToString().TrimEnd('.') + r["Message"].ToString().Substring(3);
                                    entries.Rows.Remove(r);
                                }
                            }
                        }
                    }
                }
                return entries;
            }
            catch(Exception ex)
            {
                return null;
            }
        }
    }
}
